#include "output.h"
#include <iostream>
#include <fstream>
#include "Face.h"
#include "Edge.h"
#include "Vertex.h"
color getColor(double percent)
{
    color c;
    double p=percent*6;
    p=p-(int)p;
    c.r=(int)(255*p*p*p);
    c.g=(int)(255*p*p);
    c.b=(int)(255*p);
    return c;
}
void writeToPly(std::string filename, std::vector<Vertex *>& vlist, std::vector<Face *>& flist, std::map<Vertex *, std::pair<double, Vertex *> >& outcome)
{
    std::ofstream outfile(filename.c_str(),std::fstream::out);
    std::cout<<"WRITING HEADER"<<std::endl;
    outfile<<"ply"<<std::endl;
    outfile<<"format ascii 1.0"<<std::endl;
    outfile<<"element vertex "<<vlist.size()<<std::endl;
    outfile<<"property float x"<<std::endl;
    outfile<<"property float y"<<std::endl;
    outfile<<"property float z"<<std::endl;
    outfile<<"property uchar red"<<std::endl;
    outfile<<"property uchar green"<<std::endl;
    outfile<<"property uchar blue"<<std::endl;
    outfile<<"element face "<<flist.size()<<std::endl;
    outfile<<"property list uchar int vertex_index"<<std::endl;
    outfile<<"end_header"<<std::endl;

    double max_distance=0;
    std::cout<<"CALCULATING MAX DISTANCE"<<std::endl;
    for (std::map<Vertex *,std::pair<double, Vertex *> >::iterator it=outcome.begin();it!=outcome.end();++it)
    {
        if ((it->second).first>max_distance)
            max_distance=(it->second).first;
    }
    std::cout<<"WRITING VERTEX"<<std::endl;
    for (std::vector<Vertex *>::iterator it=vlist.begin();it!=vlist.end();++it)
    {
        double c=outcome[(*it)].first/max_distance;
        outfile<<(*it)->x<<" "<<(*it)->y<<" "<<(*it)->z<<" ";
        color col=getColor(c);
        outfile<<col.r<<" "<<col.g<<" "<<col.b<<std::endl;
    }
    std::cout<<"WRITING FACE"<<std::endl;
    std::fstream lo("log.txt",std::fstream::out);
    for (std::vector<Face *>::iterator it=flist.begin();it!=flist.end();++it)
    {
        Vertex *v1=(*it)->e1->v1;
        Vertex *v2=(*it)->e1->v2;
        Vertex *v3=(*it)->e2->v1;
        if (v3==v1||v3==v2) v3=(*it)->e2->v2;
        lo<<*v1<<"\t"<<*v2<<"\t"<<*v3<<std::endl;
        outfile<<"3 "<<v1->id-1<<" "<<v2->id-1<<" "<<v3->id-1<<std::endl;
    }
    lo.close();
    outfile.close();
}

void writeToM(std::string filename,std::vector<Vertex *>& vlist,std::vector<Edge *>&elist, std::vector<Face *>& flist)
{
    std::ofstream outfile(filename.c_str(),std::fstream::out);
    for (std::vector<Vertex *>::iterator it=vlist.begin();it!=vlist.end();++it)
        outfile<<"Vertex "<<(*it)->id<<" "<<(*it)->x<<" "<<(*it)->y<<" "<<(*it)->z<<std::endl;
    for (std::vector<Edge *>::iterator it=elist.begin();it!=elist.end();++it)
        outfile<<"Edge "<<(*it)->id<<" "<<(*it)->v1->id<<" "<<(*it)->v2->id<<std::endl;
    for (std::vector<Face *>::iterator it=flist.begin();it!=flist.end();++it)
        outfile<<"Face "<<(*it)->id<<" "<<(*it)->e1->id<<" "<<(*it)->e2->id<<" "<<(*it)->e3->id<<std::endl;
    outfile.close();
}
